<template>
  <a-modal
    :width='1400'
    :visible='visible'
    :confirm-loading='loading'
    :title="isUpdate ? '修改喷淋规则配置' : '新建喷淋规则配置'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible='updateVisible'
    @ok='save'
  >
    <div class='ele-body ele-body-card'>
      <a-alert
        message="警告"
        type="warning"
        show-icon
        style="margin-bottom: 16px"
        :description-style="{ whiteSpace: 'pre-line' }"
      >
        <template #description>
          <div class="alert-description">
            <p>①不受时间控制+间歇喷淋+无算法: 不受时间段控制;没有算法,根据`喷淋时长`和`间隔时长`配置进行轮询喷淋,喷x秒,停x秒,不断的轮询</p>          
            <p>②指定时间段喷淋+无间歇+无算法: 在指定的时间段内喷淋,不在时间段内不喷淋;没有算法,不会根据`喷淋时长`和`间隔时长`配置进行喷x秒停x秒</p>          
            <p>③不受时间控制+间歇喷淋+有算法: 不受时间段控制;有算法,相机在识别到牛的情况下,根据在`喷淋时长`和`间隔时长`配置,喷x秒停x秒进行不断的轮询;识别不到牛,就不会喷</p>
            <p>④指定时间段喷淋+无间歇+有算法: 有算法,在指定的喷淋时间段内,识别到牛就喷,没牛就不喷。不在喷淋时间段,有无牛都停。不会根据`喷淋时长`和`间隔时长`配置进行喷x秒停x秒</p>     
            <p>⑤不受时间控制+无间歇+有算法: 不受时间段控制;有算法,识别到牛就喷,识别不到牛就不喷,不会根据`喷淋时长`和`间隔时长`配置进行喷x秒停x秒</p>
            <p class="warning">同步到相机的操作会覆盖相机当前的喷淋配置，会直接把喷淋时间段覆盖，请谨慎操作！</p>
            <p>保存到数据库会作为调度过程中的一些默认项</p>
          </div>
        </template>
      </a-alert>
      <a-form
          ref='formRef'
          :model='form'
          :rules="formRules"
          :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
          :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        >
          <a-row :gutter="8">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item label='模板名称:' name='templateName'>
                <a-input v-model:value='form.templateName' allow-clear style="width: 400px;" />
              </a-form-item>
            </a-col>
            <a-col :md="10" :sm="24" :xs="24" />
          </a-row>
          <a-row :gutter='8'>
            <a-col :md='12' :sm='24' :xs='24'>
              <a-form-item label='喷淋时长(秒):' name='spray'>
                <a-input-number v-model:value='form.spray' placeholder='请输入喷淋时长' :min="0" />
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'/>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='12' :sm='24' :xs='24'>
              <a-form-item label='识别容忍度(秒):' name='identify'>
                <a-input-number v-model:value='form.identify' placeholder='请输入识别容忍度' :min="0" />
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'/>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='12' :sm='24' :xs='24'>
              <a-form-item label='间隔时长(秒):' name='sprayInterval'>
                <a-input-number v-model:value='form.sprayInterval' placeholder='请输入间隔时长' :min="0" />
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'/>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='12' :sm='24' :xs='24'>
              <a-form-item label='喷淋模式:' name='ignoreAlg'>
                <a-select v-model:value="form.ignoreAlg">
                  <a-select-option :value="0">请选择</a-select-option>
                  <a-select-option :value="1">不受时间控制+间歇喷淋+无算法[旧版本：传统喷淋]</a-select-option>
                  <a-select-option :value="2">指定时间段喷淋+无间歇+无算法[旧版本：视觉喷淋]</a-select-option>
                  <a-select-option :value="3">不受时间控制+间歇喷淋+有算法[旧版本：传统喷淋+视觉喷淋]</a-select-option>
                  <a-select-option :value="4">指定时间段喷淋+无间歇+有算法</a-select-option>
                  <a-select-option :value="5">不受时间控制+无间歇+有算法</a-select-option>
                  <a-select-option :value="127">不喷淋</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'/>
          </a-row>

          <!-- 新增时间段配置 -->
          <a-row :gutter='8'>
            <a-col :md='12' :sm='24' :xs='24'>
              <a-form-item label='喷淋时间段:' name='timeSlot'>
                <div>
                  <div v-for="(timeRange, index) in form.timeSlot" :key="index" style="display: flex; margin-bottom: 8px; align-items: center;">
                    <a-time-picker 
                      v-model:value="timeRange[0]" 
                      format="HH:mm:ss" 
                      placeholder="开始时间"
                      style="width: 150px; margin-right: 8px;"
                      @change="(time) => updateTimeSlot(index, 0, time)"
                    />
                    <a-form-item-rest>
                      <span style="margin: 0 8px;">至</span>
                      <a-time-picker 
                        v-model:value="timeRange[1]" 
                        format="HH:mm:ss" 
                        placeholder="结束时间"
                        style="width: 150px; margin-right: 8px;"
                        @change="(time) => updateTimeSlot(index, 1, time)"
                      />
                      <a-button 
                        type="danger" 
                        shape="circle"
                        @click="removeTimeSlot(index)"
                      >
                        <template #icon><delete-outlined /></template>
                      </a-button>
                    </a-form-item-rest>
                  </div>
                  <a-button type="dashed" style="width: 100%; margin-top: 8px;" @click="addTimeSlot">
                    <plus-outlined /> 添加时间段
                  </a-button>
                </div>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
    </div>
  </a-modal>
</template>

<script>
import { message } from 'ant-design-vue';
import {DeviceSprayCameraStaticConfigTemplateApi} from "@/api/property/spraycamera/DeviceSprayCameraStaticConfigTemplateApi";
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';

export default {
  name: 'DeviceSpraycameraSoftwareSprayruleTemplateEdit',
  components: {
    PlusOutlined,
    DeleteOutlined
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    data: Object
  },
  created() {
    if (this.data) {
      this.form.spray = this.data.spray;
      this.form.identify = this.data.identify;
      this.form.sprayInterval = this.data.sprayInterval;
      this.form.ignoreAlg = this.data.ignoreAlg;
      this.form.scsctId = this.data.scsctId;
      this.form.templateName = this.data.templateName;
      // 初始化时间段数据 - 将JSON字符串转为数组
      if (this.data.timeSlot) {
        try {
          // 尝试解析JSON字符串
          const timeSlotArray = JSON.parse(this.data.timeSlot);
          if (Array.isArray(timeSlotArray)) {
            this.form.timeSlot = timeSlotArray.map(slot => {
              return [
                slot[0] ? dayjs(slot[0], 'HH:mm:ss') : null,
                slot[1] ? dayjs(slot[1], 'HH:mm:ss') : null
              ];
            });
          } else {
            this.form.timeSlot = [];
          }
        } catch (e) {
          console.error('解析timeSlot失败:', e);
          this.form.timeSlot = [];
        }
        this.isUpdate = true;
      } else {
        this.form.timeSlot = [];
      }
    } else {
      this.form = {
        timeSlot : []
      };
      this.isUpdate = false;
    }
  },
  data() {
    return {
      loading : false,
      form: {
        timeSlot: []
      },
      isUpdate: false,
      formRules : {}
    };
  },
  methods: {    
    // 添加时间段
    addTimeSlot() {
      this.form.timeSlot.push([null, null]);
    },
    
    // 删除时间段
    removeTimeSlot(index) {
      this.form.timeSlot.splice(index, 1);
    },
    
    // 更新时间段
    updateTimeSlot(index, position, time) {
      this.form.timeSlot[index][position] = time;
    },
    
    // 格式化时间段数据用于保存 - 转为JSON字符串
    formatTimeSlotForSave() {
      const formattedTimeSlot = this.form.timeSlot.map(slot => {
        return [
          slot[0] ? slot[0].format('HH:mm:ss') : null,
          slot[1] ? slot[1].format('HH:mm:ss') : null
        ];
      }).filter(slot => slot[0] && slot[1]); // 过滤掉不完整的时间段
      
      // 将数组转为JSON字符串
      return JSON.stringify(formattedTimeSlot);
    },

    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    

    save() {
      let that = this;
      this.loading = true;
      
      // 格式化时间段数据为JSON字符串
      const formData = {...that.form};
      formData.timeSlot = that.formatTimeSlotForSave();

      // 修改加载框为正在加载
      this.loading = true;
      let result = null;
      // 执行编辑或修改
      if (that.isUpdate) {
        result = DeviceSprayCameraStaticConfigTemplateApi.edit(formData);
      } else {
        result = DeviceSprayCameraStaticConfigTemplateApi.add(formData);
      }
      result.then(res => {
          // 移除加载框
          that.loading = false;
          // 提示添加成功
          message.success(res.message);
          // 如果是新增，则form表单置空
          if (!that.isUpdate) {
            this.form = {};
          }
          // 关闭弹框，通过控制visible的值，传递给父组件
          that.updateVisible(false);
          // 触发父组件done事件
          that.$emit('done');
        })
        .catch(() => {
          that.loading = false;
        });
    },

    
    


  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
